package com.sdry.project.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sdry.exception.BizException;
import com.sdry.project.entity.ProjectExpert2023;
import com.sdry.project.entity.ProjectExpertEntity;
import com.sdry.project.mapper.ProjectExpert2023Mapper;
import com.sdry.project.mapper.ProjectExpertMapper;
import com.sdry.project.service.ProjectExpertService;
import com.sdry.system.entity.SysUser;
import com.sdry.untils.StringUtil;
import com.sdry.untils.UserContext;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author chenBin
 * @since 2020-08-10
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class ProjectExpertServiceImpl extends ServiceImpl<ProjectExpertMapper, ProjectExpertEntity> implements ProjectExpertService {

    @Resource
    private ProjectExpertMapper projectExpertMapper;
    @Resource
    private ProjectExpert2023Mapper projectExpert2023Mapper;

    @Override
    public boolean add(Long projectId, String userId) {
        extracted(projectId, userId);
        return true;
    }



    @Override
    public boolean add2023(String projectIds, String userIds) {
        String[] projectIdSplit = projectIds.split(",");
        for (String projectId : projectIdSplit) {
            if (StringUtil.isNotEmpty(projectId)) {
                extracted2023(Long.parseLong(projectId), userIds);
            }
        }
        return true;
    }

    @Override
    public boolean approvalNext(String projectIds) {
        //projectExpert2023Mapper.selectProjectExpert2023List()
        // 原来的数据拿到
        List<ProjectExpertEntity> oldList = new ArrayList<>();
        for (String projectId : projectIds.split(",")) {
            QueryWrapper<ProjectExpertEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ProjectExpertEntity::getProjectId, projectId)
                    .eq(ProjectExpertEntity::getDelFlag,0);
            List<ProjectExpertEntity> projectExpertEntities = projectExpertMapper.selectList(queryWrapper);
            oldList.addAll(projectExpertEntities);
        }
        for (String projectId : projectIds.split(",")) {
            // 先删除已存在的，然后再添加
            QueryWrapper<ProjectExpert2023> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ProjectExpert2023::getProjectId,projectId);
            int delete = projectExpert2023Mapper.delete(queryWrapper);
        }
        // 插入到现在二次评审表
        for (ProjectExpertEntity projectExpertEntity : oldList) {
            ProjectExpert2023 projectExpert2023 = new ProjectExpert2023();
            projectExpert2023.setProjectId(projectExpertEntity.getProjectId());
            projectExpert2023.setUserId(projectExpertEntity.getUserId());
            projectExpert2023.setCreateBy(UserContext.getSessionUserNameByServiceImpl());
            projectExpert2023Mapper.insertProjectExpert2023(projectExpert2023);
        }
        return true;
    }

    @Override
    public String listUserRelName(Long projectId) {
        List<SysUser> sysUserList =  projectExpertMapper.listUserRelName(projectId);
        StringBuilder realName = new StringBuilder();
        for (SysUser sysUser : sysUserList) {
            realName.append(" ");
            realName.append(sysUser.getRealName());
        }
        return realName.toString();
    }

    @Override
    public boolean updateExpertRecall(Long id) {
        ProjectExpertEntity projectExpertEntity = new ProjectExpertEntity();
        projectExpertEntity.setId(id);
        projectExpertEntity.setState("0");
        projectExpertEntity.setLevel(0);
        int update = projectExpertMapper.updateById(projectExpertEntity);
        return update > 0;
    }

    /**
     * 根据登录用户（专家）查询所关联的项目
     * @param projectExpertEntity 查询实体
     * @return 查询结果集
     */
    @Override
    public List<ProjectExpertEntity> listByUid(ProjectExpertEntity projectExpertEntity) {
        return projectExpertMapper.listByUid(projectExpertEntity);
    }

    /**
     * 图表查询
     * @param pid 项目id
     * @return 查询结果
     */
    @Override
    public List<ProjectExpertEntity> chart(Long pid) {
        return projectExpertMapper.chart(pid);
    }

    @Override
    public List<ProjectExpertEntity> listByUidNotExpert(ProjectExpertEntity projectExpertEntity) {
        return projectExpertMapper.listByUidNotExpert(projectExpertEntity);
    }

    @Override
    public List<ProjectExpertEntity> chart2021(Long pid) {
        return projectExpertMapper.cchart2021(pid);
    }

    @Override
    public boolean updateExpertRecall2021(Long id) {
        ProjectExpertEntity projectExpertEntity = new ProjectExpertEntity();
        projectExpertEntity.setId(id);
        projectExpertEntity.setState("0");
        //projectExpertEntity.setLevel(0);
        projectExpertEntity.setEvaluationOpinion(null);
        projectExpertEntity.setScoring(null);
        int update = projectExpertMapper.updateById2021(projectExpertEntity);
        return update > 0;
    }

    private void extracted2023(Long projectId, String userId) {
        // 先删除数据
        int effect = projectExpertMapper.deleteByProjectId(projectId);
        //projectExpertMapper.delete(new QueryWrapper<ProjectExpertEntity>().lambda().eq(ProjectExpertEntity::getProject,projectId));
        List<Long> longListId = new ArrayList<>();
        String[] split = userId.split(",");
        for (String id : split) {
            if ("on".equals(id)){
                continue;
            }
            longListId.add(Long.parseLong(id));
            QueryWrapper<ProjectExpertEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ProjectExpertEntity::getProjectId, projectId)
                    .eq(ProjectExpertEntity::getUserId,id)
                    .eq(ProjectExpertEntity::getDelFlag,0);
            List<ProjectExpertEntity> projectExpertEntities = projectExpertMapper.selectList(queryWrapper);
            //判断是否已经存在，存在--不动,  ， 不存在--添加
            if (projectExpertEntities.size() == 0) {
                ProjectExpertEntity projectExpertEntity = new ProjectExpertEntity();
                projectExpertEntity.setProjectId(projectId);
                projectExpertEntity.setUserId(Long.parseLong(id));
                projectExpertEntity.setCreateBy(UserContext.getSessionUserNameByServiceImpl());
                int insert = projectExpertMapper.insert(projectExpertEntity);
                if (insert == 0) {
                    throw new BizException("增删改查失败");
                }
            }
        }

        //查询所有的专家
        QueryWrapper<ProjectExpertEntity> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.lambda().eq(ProjectExpertEntity::getProjectId, projectId)
                .eq(ProjectExpertEntity::getDelFlag,0);
        List<ProjectExpertEntity> projectExpertEntityList = projectExpertMapper.selectList(queryWrapper2);
        if (projectExpertEntityList.size() > 0) {
            for (ProjectExpertEntity projectExpertEntity : projectExpertEntityList) {
                if (!longListId.contains(projectExpertEntity.getUserId())) {
                    QueryWrapper<ProjectExpertEntity> queryWrapper3 = new QueryWrapper<>();
                    queryWrapper3.lambda().eq(ProjectExpertEntity::getUserId,projectExpertEntity.getUserId())
                            .eq(ProjectExpertEntity::getProjectId, projectId);
                    ProjectExpertEntity projectExpertEntity3 = new ProjectExpertEntity();
                    projectExpertEntity3.setDelFlag("1");
                    projectExpertEntity3.setUpdateBy(UserContext.getSessionUserNameByServiceImpl());
                    projectExpertEntity3.setUpdateDate(new Timestamp(System.currentTimeMillis()));
                    int update = projectExpertMapper.update(projectExpertEntity3, queryWrapper3);
                    if (update == 0) {
                        throw new BizException("增删改查失败");
                    }
                }
            }
        }
    }

    private void extracted(Long projectId, String userId) {
        List<Long> longListId = new ArrayList<>();
        String[] split = userId.split(",");
        for (String id : split) {
            if ("on".equals(id)){
                continue;
            }
            longListId.add(Long.parseLong(id));
            QueryWrapper<ProjectExpertEntity> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(ProjectExpertEntity::getProjectId, projectId)
                    .eq(ProjectExpertEntity::getUserId,id)
                    .eq(ProjectExpertEntity::getDelFlag,0);
            List<ProjectExpertEntity> projectExpertEntities = projectExpertMapper.selectList(queryWrapper);
            //判断是否已经存在，存在--不动  ， 不存在--添加
            if (projectExpertEntities.size() == 0) {
                ProjectExpertEntity projectExpertEntity = new ProjectExpertEntity();
                projectExpertEntity.setProjectId(projectId);
                projectExpertEntity.setUserId(Long.parseLong(id));
                projectExpertEntity.setCreateBy(UserContext.getSessionUserNameByServiceImpl());
                int insert = projectExpertMapper.insert(projectExpertEntity);
                if (insert == 0) {
                    throw new BizException("增删改查失败");
                }
            }
        }

        //查询所有的专家
        QueryWrapper<ProjectExpertEntity> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.lambda().eq(ProjectExpertEntity::getProjectId, projectId)
                .eq(ProjectExpertEntity::getDelFlag,0);
        List<ProjectExpertEntity> projectExpertEntityList = projectExpertMapper.selectList(queryWrapper2);
        if (projectExpertEntityList.size() > 0) {
            for (ProjectExpertEntity projectExpertEntity : projectExpertEntityList) {
                if (!longListId.contains(projectExpertEntity.getUserId())) {
                    QueryWrapper<ProjectExpertEntity> queryWrapper3 = new QueryWrapper<>();
                    queryWrapper3.lambda().eq(ProjectExpertEntity::getUserId,projectExpertEntity.getUserId())
                            .eq(ProjectExpertEntity::getProjectId, projectId);
                    ProjectExpertEntity projectExpertEntity3 = new ProjectExpertEntity();
                    projectExpertEntity3.setDelFlag("1");
                    projectExpertEntity3.setUpdateBy(UserContext.getSessionUserNameByServiceImpl());
                    projectExpertEntity3.setUpdateDate(new Timestamp(System.currentTimeMillis()));
                    int update = projectExpertMapper.update(projectExpertEntity3, queryWrapper3);
                    if (update == 0) {
                        throw new BizException("增删改查失败");
                    }
                }
            }
        }
    }
}
